<template>
  <div class="dashboard-container">
    <!-- 第一行：最近使用 + 待办中心 -->
    <el-row :gutter="10" class="row-recent">
      <el-col :xs="24" :md="16">
        <DashboardCard title="最近使用">
          <el-card shadow="hover">
            <app-list1 :apps="recentApps" @click-app="handleAppClick" />
          </el-card>
        </DashboardCard>
      </el-col>
      <el-col :xs="24" :md="8">
        <DashboardCard title="消息中心">
          <el-card shadow="hover">
            <news-list :news="news" />
          </el-card>
        </DashboardCard>
      </el-col>
    </el-row>

    <!-- 第二行：应用中心 -->
    <el-row :gutter="10" class="row-app-center mt-20">
      <el-col>
        <DashboardCard title="应用中心">
          <el-card shadow="hover">
            <app-list :apps="allApps1" @click-app="handleAppClick" />
          </el-card>
        </DashboardCard>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import DashboardCard from "./components/DashboardCard.vue";
import AppList from "./components/AppList.vue";
import AppList1 from "./components/AppList1.vue";
import TodoList from "./components/TodoList";
import NewsList from "./components/NewsList";
import { fetchNotifications } from "@/api/notification";

export default {
  name: "Dashboard",
  components: {
    DashboardCard,
    AppList,
    AppList1,
    TodoList,
    NewsList,
  },
  data() {
    return {
      userId: null, // 用户ID
      // 保留完整映射
      fullRouteMap: {
        项目管理: "/menus/project",
        验收规范管理: "/menus/inspection",
        台账管理: "/menus/ledger",
        报表管理: "/menus/statement",
        数据采集情况: "/menus/collection",
        数据采集任务: "/menus/task",
        OCR模版库: "/menus/ocrTemplate",
        角色管理: "/menus/roles",
        人员管理: "/menus/users",
        计划表管理: "/menus/schedule",
      },
      routeMap: {}, // 根据权限过滤后的映射
      recentApps: [],
      allApps: [
        { id: 1, name: "项目管理", icon: "program" },
        { id: 2, name: "验收规范管理", icon: "specification" },
        { id: 3, name: "台账管理", icon: "ledger" },
        { id: 4, name: "报表管理", icon: "statement" },
        { id: 5, name: "数据采集情况", icon: "dataCollection" },
        { id: 6, name: "数据采集任务", icon: "task" },
        { id: 7, name: "OCR模版库", icon: "ocr" },
        { id: 8, name: "计划表管理", icon: "schedule" },
        { id: 9, name: "角色管理", icon: "role1" },
        { id: 10, name: "人员管理", icon: "role" },
      ],
      allApps1: [],
      allApps2: [],
      todos: [
        {
          id: 1,
          title: "完成项目审核",
          deadline: "2023-05-20",
          completed: false,
        },
        {
          id: 2,
          title: "项目采集",
          deadline: "2023-05-18",
          completed: false,
        },
        {
          id: 3,
          title: "安排团队建设活动",
          deadline: "2023-05-25",
          completed: false,
        },
      ],
      news: [],
    };
  },
  created() {
    // 获取用户ID
    const user = JSON.parse(localStorage.getItem("user") || "{}");
    this.userId = user.userId;

    // 加载最近使用
    const stored = localStorage.getItem("recentApps");
    if (stored) {
      this.recentApps = JSON.parse(stored);
    }

    // Vue 2 使用 this.$router.options.routes
    const allowedPaths = [];
    this.$router.options.routes.forEach((route) => {
      if (route.path === "/menus") {
        // console.log(route.path)
        if (route.children) {
          route.children.forEach((child) =>
            allowedPaths.push("/menus/" + child.path)
          );
        }
      }
    });
    // 过滤当前用户能访问的 routeMap
    const filtered = {};
    for (const [appName, path] of Object.entries(this.fullRouteMap)) {
      if (allowedPaths.includes(path)) {
        filtered[appName] = path;
      }
    }
    this.routeMap = filtered;

    const allowedAppNames = Object.keys(this.routeMap);
    const allowedApps = this.allApps.filter((app) =>
      allowedAppNames.includes(app.name)
    );
    this.allApps1 = allowedApps;
    // const mid = Math.ceil(allowedApps.length / 2);
    // this.allApps= allowedApps.slice(0, mid);
    // this.allApps2 = allowedApps.slice(mid);

    // 加载最新消息
    this.loadLatestNews();

    // 开始轮询新消息
    this.startNewsPolling();
  },
  beforeDestroy() {
    // 停止轮询
    this.stopNewsPolling();
  },
  methods: {
    handleAppClick(app) {
      const routePath = this.routeMap[app.name];
      if (routePath) {
        this.$router.push(routePath);
      } else {
        this.$message.warning("您没有权限访问该应用");
      }

      // 更新最近使用
      const index = this.recentApps.findIndex((item) => item.id === app.id);
      if (index !== -1) {
        this.recentApps[index].usedAt = new Date().toISOString().split("T")[0];
      } else {
        this.recentApps.unshift({
          ...app,
          usedAt: new Date().toISOString().split("T")[0],
        });
        if (this.recentApps.length > 4) {
          this.recentApps.pop();
        }
      }

      // 排序 & 存储
      this.recentApps.sort((a, b) => new Date(b.usedAt) - new Date(a.usedAt));
      localStorage.setItem("recentApps", JSON.stringify(this.recentApps));
    },
    handleCompleteTodo(todo) {
      const index = this.todos.findIndex((item) => item.id === todo.id);
      if (index !== -1) {
        this.todos[index].completed = true;
      }
    },
    // 加载最新消息
    async loadLatestNews() {
      if (!this.userId) return;

      try {
        // 先获取未读消息
        const unreadResponse = await fetchNotifications({
          userId: this.userId,
          notificationType: 4, // 4-未读消息
          pageSize: 10, // 获取更多未读消息以确保有足够的选择
        });

        let news = [];

        if (unreadResponse.success && unreadResponse.result) {
          // 获取前两条未读消息
          const unreadNews = unreadResponse.result.slice(0, 2).map((item) => ({
            id: item.userNotificationId,
            title: item.title,
            date: this.formatDate(item.createdAt),
            isNew: true,
          }));

          news = unreadNews;

          // 如果未读消息不足两条，补充最新消息
          if (unreadNews.length < 2) {
            const remainingCount = 2 - unreadNews.length;

            // 获取最新消息（包括已读和未读）
            const latestResponse = await fetchNotifications({
              userId: this.userId,
              pageSize: 10, // 获取更多消息以确保有足够的选择
            });

            if (latestResponse.success && latestResponse.result) {
              // 过滤掉已经在未读消息中的，并获取最新的几条
              const existingIds = unreadNews.map((item) => item.id);
              const additionalNews = latestResponse.result
                .filter(
                  (item) => !existingIds.includes(item.userNotificationId)
                )
                .slice(0, remainingCount)
                .map((item) => ({
                  id: item.userNotificationId,
                  title: item.title,
                  date: this.formatDate(item.createdAt),
                  isNew: !item.isRead,
                }));

              news = [...unreadNews, ...additionalNews];
            }
          }
        } else {
          // 如果没有未读消息，直接获取最新消息
          const latestResponse = await fetchNotifications({
            userId: this.userId,
            pageSize: 2,
          });

          if (latestResponse.success && latestResponse.result) {
            news = latestResponse.result.map((item) => ({
              id: item.userNotificationId,
              title: item.title,
              date: this.formatDate(item.createdAt),
              isNew: !item.isRead,
            }));
          }
        }

        this.news = news;
      } catch (error) {
        console.error("加载最新消息失败:", error);
      }
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return "";
      const date = new Date(dateString);
      return date.toLocaleDateString("zh-CN");
    },

    // 开始轮询新消息
    startNewsPolling() {
      this.stopNewsPolling(); // 先停止之前的轮询
      this.newsPollingTimer = setInterval(() => {
        this.pollNewNews();
      }, 5 * 60 * 1000); // 5分钟轮询一次
    },

    // 停止轮询
    stopNewsPolling() {
      if (this.newsPollingTimer) {
        clearInterval(this.newsPollingTimer);
        this.newsPollingTimer = null;
      }
    },

    // 轮询新消息
    async pollNewNews() {
      if (!this.userId) return;

      try {
        // 先获取未读消息
        const unreadResponse = await fetchNotifications({
          userId: this.userId,
          notificationType: 4, // 4-未读消息
          pageSize: 10, // 获取更多未读消息以确保有足够的选择
        });

        let newNews = [];

        if (unreadResponse.success && unreadResponse.result) {
          // 获取前两条未读消息
          const unreadNews = unreadResponse.result.slice(0, 2).map((item) => ({
            id: item.userNotificationId,
            title: item.title,
            date: this.formatDate(item.createdAt),
            isNew: true,
          }));

          newNews = unreadNews;

          // 如果未读消息不足两条，补充最新消息
          if (unreadNews.length < 2) {
            const remainingCount = 2 - unreadNews.length;

            // 获取最新消息（包括已读和未读）
            const latestResponse = await fetchNotifications({
              userId: this.userId,
              pageSize: 10, // 获取更多消息以确保有足够的选择
            });

            if (latestResponse.success && latestResponse.result) {
              // 过滤掉已经在未读消息中的，并获取最新的几条
              const existingIds = unreadNews.map((item) => item.id);
              const additionalNews = latestResponse.result
                .filter(
                  (item) => !existingIds.includes(item.userNotificationId)
                )
                .slice(0, remainingCount)
                .map((item) => ({
                  id: item.userNotificationId,
                  title: item.title,
                  date: this.formatDate(item.createdAt),
                  isNew: !item.isRead,
                }));

              newNews = [...unreadNews, ...additionalNews];
            }
          }
        } else {
          // 如果没有未读消息，直接获取最新消息
          const latestResponse = await fetchNotifications({
            userId: this.userId,
            pageSize: 2,
          });

          if (latestResponse.success && latestResponse.result) {
            newNews = latestResponse.result.map((item) => ({
              id: item.userNotificationId,
              title: item.title,
              date: this.formatDate(item.createdAt),
              isNew: !item.isRead,
            }));
          }
        }

        // 检查是否有新消息
        if (JSON.stringify(newNews) !== JSON.stringify(this.news)) {
          this.news = newNews;
          // 显示新消息提示
          this.$message && this.$message.success("收到新消息");
        }
      } catch (error) {
        console.error("轮询新消息失败:", error);
      }
    },
  },
};
</script>


<style scoped>
.row-recent {
  margin-bottom: 5px;
}

.row-recent .el-card {
  height: 150px;
  overflow: auto;
}

.row-app-center .el-card {
  height: 550px;
  /* 主功能最大 */
  overflow: auto;
}

.mt-20 {
  margin-top: 20px;
}
</style>
